package com.shiwaixiangcun.customer.module.mall;

import android.os.Bundle;
import android.support.constraint.ConstraintLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.reflect.TypeToken;
import com.jaeger.recyclerviewdivider.RecyclerViewDivider;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.shiwaixiangcun.customer.GlobalApi;
import com.shiwaixiangcun.customer.GlobalConfig;
import com.shiwaixiangcun.customer.R;
import com.shiwaixiangcun.customer.adapter.AdapterAfterService;
import com.shiwaixiangcun.customer.base.BaseActivity;
import com.shiwaixiangcun.customer.entity.AfterServiceBean;
import com.shiwaixiangcun.customer.entity.ResponseEntity;
import com.shiwaixiangcun.customer.utils.AppSharePreferenceMgr;
import com.shiwaixiangcun.customer.utils.JsonUtil;
import com.shiwaixiangcun.customer.utils.RefreshTokenUtil;
import com.shiwaixiangcun.customer.widget.ChangeLightImageView;
import com.shiwaixiangcun.customer.widget.CustomLoadMoreView;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 售后服务页面
 *
 * @author Administrator
 */

public class AfterServiceActivity extends BaseActivity {


    @BindView(R.id.back_left)
    ChangeLightImageView mBackLeft;
    @BindView(R.id.tv_page_name)
    TextView mTvPageName;
    @BindView(R.id.rv_after_service)
    RecyclerView mRvAfterService;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout mRefreshLayout;
    @BindView(R.id.cl_nodata)
    ConstraintLayout mClNodata;
    private AdapterAfterService mAdapterAfterService;
    private List<AfterServiceBean.ElementsBean> mAfterServiceList;
    private String tokenString;
    private String refreshToken;

    private int mCurrentPage = GlobalConfig.first_page;
    private int mPageSize = GlobalConfig.page_size;

    public AfterServiceActivity() {
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_after_service);

//        EventBus.getDefault().register(this);
        ButterKnife.bind(this);
        initToken();
        initViewAndEvent();
        requestData(false);
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void updateUI(a saleEvent) {
//        if (saleEvent.isOk()) {
//            mAfterServiceList.addAll(saleEvent.getBean().getData().getElements());
//            mAdapterAfterService.notifyDataSetChanged();
//        }
//
//    }

    @Override
    protected void onDestroy() {
//        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        initToken();
        mCurrentPage = 1;
        requestData(false);
    }

    private void initToken() {
        refreshToken = (String) AppSharePreferenceMgr.get(mContext, GlobalConfig.Refresh_token, "");
        tokenString = (String) AppSharePreferenceMgr.get(mContext, GlobalConfig.TOKEN, "");
    }

    /**
     * 请求数据
     *
     * @param isLoadMore
     */
    private void requestData(final boolean isLoadMore) {

        OkGo.<String>get(GlobalApi.INSTANCE.getAfterService())
                .params("access_token", tokenString)
                .params("page.pn", mCurrentPage)
                .params("page.size", mPageSize)
                .execute(new StringCallback() {

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        mRefreshLayout.finishRefresh();
                        mAdapterAfterService.setEnableLoadMore(true);
                        mAdapterAfterService.loadMoreFail();
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        mAdapterAfterService.setEnableLoadMore(true);
                        Type type = new TypeToken<ResponseEntity<AfterServiceBean>>() {
                        }.getType();

                        ResponseEntity<AfterServiceBean> responseEntity = JsonUtil.fromJson(response.body(), type);
                        if (responseEntity == null) {
                            return;

                        }
                        switch (responseEntity.getResponseCode()) {
                            case 1001:

                                int size = responseEntity.getData().getElements().size();
                                if (isLoadMore) {
                                    if (size > 0) {
                                        mAfterServiceList.addAll(responseEntity.getData().getElements());
                                        mAdapterAfterService.notifyDataSetChanged();
                                    }
                                    if (size == 0 || size < mPageSize) {
                                        mAdapterAfterService.loadMoreEnd(false);
                                    } else {
                                        mAdapterAfterService.loadMoreComplete();
                                    }
                                } else {
                                    mRefreshLayout.finishRefresh();
                                    mAdapterAfterService.setEnableLoadMore(true);
                                    if (size == 0) {
                                        mClNodata.setVisibility(View.VISIBLE);
                                    } else {
                                        mAfterServiceList.clear();
                                        mAfterServiceList.addAll(responseEntity.getData().getElements());
                                        mAdapterAfterService.notifyDataSetChanged();
                                    }
                                }
                                break;
                            case 1018:
                                RefreshTokenUtil.refreshToken(mContext, refreshToken);
                                break;
                            default:
                                break;
                        }

                    }
                });


    }

    private void initViewAndEvent() {
        mTvPageName.setText(R.string.after_service);
        mBackLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });


        mAfterServiceList = new ArrayList<>();
        mAdapterAfterService = new AdapterAfterService(mAfterServiceList);
        mRvAfterService.setLayoutManager(new LinearLayoutManager(mContext));
        mRvAfterService.setAdapter(mAdapterAfterService);

        RecyclerViewDivider divider = new RecyclerViewDivider.Builder(mContext)
                .setOrientation(RecyclerViewDivider.VERTICAL)
                .setStyle(RecyclerViewDivider.Style.BETWEEN)
                .setEndSkipCount(1)
                .setSize(16f)
                .setColorRes(R.color.ui_gray)
                .build();
        mRvAfterService.addItemDecoration(divider);

        mAdapterAfterService.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                AfterServiceBean.ElementsBean bean = (AfterServiceBean.ElementsBean) adapter.getData().get(position);
                Bundle bundle = new Bundle();
                bundle.putInt("id", bean.getId());
                readyGo(AfterDetailActivity.class, bundle);
            }
        });

        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                mCurrentPage = 1;
                requestData(false);
                mAdapterAfterService.setEnableLoadMore(false);
            }
        });


        mAdapterAfterService.setLoadMoreView(new CustomLoadMoreView());
        mAdapterAfterService.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                mCurrentPage += 1;
                requestData(true);
            }
        }, mRvAfterService);

    }
}
